// pages/article-detail/index.js
var pay = require('./../../utils/pay.js').default

var WxParse = require('../../utils/wxParse/wxParse.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        lession: {},
        user: wx.getStorageSync('user'),
        commentList: [],
        value: '',
        isShowAll: false,
        isCanAnswer:true,//是否可以添加留言
        isShowBuyBtn:false,// 是否显示购买按钮
    },
    // 分享课程
    shareLession() {
        this.onShareAppMessage();
    },
    onLoad(option) {
        console.log(option);
        this.startTime = new Date;
        this.setData(option)
        wx.showLoading({
            title: '加载中',
        })
        wx.$ajax.getLessionDetail({courseID: +option.id, courseNumber: option.courseNumber}, {isToken: true})
            .then(({data: {data, msg, status}, header, statusCode, errMsg}) => {

                wx.hideLoading();
                if (status === '0') {
                    let {content, clipContent, feeStatus, courseType,courseProperty,chargeStatus} = data.Course;
                    if(courseProperty == 1 || courseType == 4){
                        // 公开
                        showContent.bind(this)(true);

                    }else{
                        wx.$ajax.getSystemOptions()
                            .then(({data: {data, msg, status}, header, statusCode, errMsg}) => {
                                if (status === '0') {
                                    if( data.systemSetting.isCharge){
                                        //整体收费
                                        if(feeStatus == 2){
                                            //课程收费

                                            if(chargeStatus == 1){
                                                //已购买
                                                showContent.bind(this)(true);

                                            }else{
                                                // 未购买
                                                showContent.bind(this)(false);
                                                this.setData({isShowBuyBtn:true})
                                            }
                                        }else{
                                            //课程免费
                                            showContent.bind(this)(true);
                                            this.setData({isCanAnswer:false})
                                        }
                                    }else{
                                        // 不是整体收费
                                        showContent.bind(this)(true);
                                    }
                                }else{
                                    // 请求错误时
                                    showContent.bind(this)(false);
                                }
                            })
                    }

                    this.setData({
                        lession: data.Course,
                        // 判断是否显示 购买框
                        isShowAll: courseType != 4 && feeStatus == 2
                    });
                    this.getMommentList();
                    function showContent(flag){
                        WxParse.wxParse('article', 'html', flag ? content : clipContent, this, 5);
                    }
                } else {
                    wx.showToast({
                        title: '文章已删除或不存在',
                        icon: 'none'
                    })

                    setTimeout(function () {
                        wx.hideToast();
                        wx.navigateBack();
                    }, 2000)
                }
            })

    },
    // 获取评论列表
    getMommentList() {
        let {lession} = this.data;
        wx.$ajax.getMommentList({courseID: +lession.courseID, "status": '1', start: 1, "size": 10000})
            .then(({data: {data, msg, status}, header, statusCode, errMsg}) => {
                if (status === '0') {
                    this.setData({
                        commentList: data.comment_list || []
                    })
                } else {
                    console.log('请求失败');
                }
            })
    },
    // 分享
    onShareAppMessage: function (res) {
        let {lession} = this.data;

        console.log(`/pages/article-detail/index?id=${lession.courseID}&from=share&userId=${this.data.user.userID}`)
        return {
            title: lession.title,
            path: `/pages/article-detail/index?id=${lession.courseID}&from=share&userId=${this.data.user.userID}`,
            success: function (res) {
                console.log('转发成功');
            },
            fail: function (res) {
                console.log('转发失败');
            }
        }
    },
    onUnload() {
        // 统计阅读时间
        let {data} = this;
        wx.$ajax.courseTimeUse({
            courseID: +data.id,
            startTime: (+this.startTime).toString().substr(0, 10),
            outTime: (+new Date).toString().substr(0, 10),
            useTime: (Math.floor((new Date - this.startTime) / 1000)).toString()
        }, {isToken: true})
            .then(({data: {data, msg, status}, header, statusCode, errMsg}) => {
                if (status === '0') {
                    console.log(`共阅读了${(Math.floor((new Date - this.startTime) / 1000)).toString()}秒`);
                } else {
                    console.log('统计阅读时间失败');
                }
            })
    },
    // 支付
    payMoney() {
        let {lession} = this.data;
        wx.$ajax.createOrder({
            "courseID": lession.courseID,
            "courseName": lession.courseName,
            "amount": lession.amount * 100,
            "payWay": 0,
            "type": 0
        }, {isToken: true})
            .then(({data: {data, msg, status}, header, statusCode, errMsg}) => {
                if (status === '0') {
                    pay(data).then(res => {
                        console.log(res);
                        wx.showToast({
                            title: '支付成功',
                            icon: 'none'
                        })

                    }).catch(res => {
                        wx.showToast({
                            title: '支付失败',
                            icon: 'none'
                        })
                    })
                } else {
                    wx.showToast({
                        title: msg,
                        icon: 'none'
                    })
                }
            })
    },
    // 购买全部课程
    payAllMoney() {
        wx.$ajax.createOrder({
            "payWay": 0,
            "type": 1
        }, {isToken: true})
            .then(({data: {data, msg, status}, header, statusCode, errMsg}) => {
                if (status === '0') {
                    pay(data).then(res => {
                        console.log(res);
                        wx.showToast({
                            title: '支付成功',
                            icon: 'none'
                        })
                        wx.navigateTo({
                            url:'/pages/study/class-list/index'
                        })

                    }).catch(res => {
                        wx.showToast({
                            title: '支付失败',
                            icon: 'none'
                        })
                    })
                } else {
                    wx.showToast({
                        title: msg,
                        icon: 'none'
                    })
                }
            })
    },
    // 提交评论
    bindconfirm(e) {
        let {lession} = this.data;
        if (!e.detail.value.trim()) return;
        wx.$ajax.commitMomment({
            content: e.detail.value,
            CourseId: +lession.courseID
        })

            .then(({data: {data, msg, status}, header, statusCode, errMsg}) => {
                console.log(data, msg, status, header, statusCode, errMsg);
                if (status === '0') {
                    wx.showToast({
                        icon: 'none',
                        title: '评论已上传,通过后将会显示'
                    })
                    this.setData({value: ''})

                } else {
                    wx.showToast({
                        icon: 'none',
                        title: '添加评论失败'
                    })
                }
            })
    },
    // 返回首页
    goHome(){
        wx.switchTab({
            url:'/pages/index/index'
        })
    }
})


